﻿using DataService;
using DataService.Enums;
using DataService.Structs;
using DataService.Tag;
using System;
using System.ComponentModel;

namespace CoreTest;

public class TagItem : INotifyPropertyChanged, IDisposable
{
    public TagItem(TagMetaData metadata)
    {
        _tagname = metadata.Name;
        _addr = metadata.Address;
        _tag = App.Server[_tagname];
        if (_tag != null)
        {
            _tagValue = _tag.ToString();
            _timestamp = _tag.Timestamp;
            _tag.ValueChanged += new ValueChangedEventHandler(TagValueChanged);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    TagBase _tag;

    string _tagname;
    public string TagName
    {
        get => _tagname;
        set => _tagname = value;
    }

    string _addr;
    public string Address
    {
        get => _addr;
        set => _addr = value;
    }

    string _tagValue;
    public string TagValue
    {
        get => _tagValue;
        set
        {
            if (_tagValue != value)
            {
                _tagValue = value;
                OnPropertyChanged("TagValue");
            }
        }
    }

    DateTime _timestamp;
    public DateTime Timestamp
    {
        get => _timestamp;
        set
        {
            if (_timestamp != value)
            {
                _timestamp = value;
                OnPropertyChanged("TimeStamp");
            }
        }
    }

    private void TagValueChanged(object sender, ValueChangedEventArgs args)
    {
        TagValue = _tag.ToString();
        Timestamp = _tag.Timestamp;
    }

    public int Write(string value)
    {
        if (string.IsNullOrEmpty(value))
            return -1;

        if (_tag.Address.VarType == DataType.BOOL)
        {
            if (value == "1")
                value = "true";
            if (value == "0")
                value = "false";
        }
        return _tag.Write(value);
    }

    public void SimWrite(string value)
    {
        if (string.IsNullOrEmpty(value))
            return;

        Storage stor = Storage.Empty;
        try
        {
            if (_tag.Address.VarType == DataType.STR)
            {
                ((StringTag)_tag).String = value;
            }
            else
            {
                stor = _tag.ToStorage(value);
            }
            _tag.Update(stor, DateTime.Now, QUALITIES.QUALITY_GOOD);
        }
        catch { }
    }

    public void Dispose()
    {
        if (_tag != null)
        {
            _tag.ValueChanged -= new ValueChangedEventHandler(TagValueChanged);
        }
    }
}
